<template>
  <a-card class="app">




    <a-spin :spinning="tableLoading">



      <a-row class="smart-table-btn-block">
        <div class="smart-table-operate-block">
          <a-button @click="addCategory()" type="primary" >
            <template #icon>
              <PlusOutlined />
            </template>
            新建
          </a-button>
        </div>
        <div class="smart-table-setting-block"></div>
      </a-row>













      <a-table :scroll="{ x: 600 }" :dataSource="data.tableData" rowKey="bomId" :columns="columnsa" :pagination="false"
        @expandedRowsChange="changeExand" :expanded-row-keys="expandedRowKeys">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'qty'">
            <span>{{ excute(text) }}</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="addCategory(record.id)" type="link">增加子分类</a-button>
              <a-button @click="addCategory(undefined, record)" type="link">编辑</a-button>
              <a-button @click="confirmDeleteCategory(record.categoryId)" danger type="link">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </a-spin>
  </a-card>
  <BomordFormModal ref="formModal" @reloadList="queryData" />

  <!--  <Approvord :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>-->
</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { message, Modal, Form } from 'ant-design-vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { approvordApi } from '/@/api/business/erp/approvord-api';
import { useRouter, useRoute } from 'vue-router';
import Approvord from '/@/components/business/erp/approved.vue';
import { goodsApi } from '/@/api/business/goods/goods-api.js';
import { saordApi } from '/@/api/business/erp/saord-api.js';
import { puordApi } from '/@/api/business/erp/puord-api.js';
import { bomordApi } from '/@/api/business/erp/bomord-api.js';
import BomordFormModal from "/src/views/business/erp/bas/bomord-form-modal.vue";


import { PROVINCE_CITY_DISTRICT } from '/@/components/framework/area-cascader/province-city-district.js';




import { excute } from '/@/utils/numformat-util.js';
import CategoryFormModal from "/src/views/business/erp/bas/components/category-form-modal.vue";

const route = useRoute();
const router = useRouter();
const data = reactive({
  tableData: [],
  form: {
    id: 0,
    objId: '',
    absId: '',
    approved: false,
    docStatus: 'O',
    vendId: null,
    vendName: null,
    deptId: null,
    deptName: null,
    edit: false,
    objName: null,
    province: null,
    provinceName: null,
    city: null,
    cityName: null,
    district: null,
    districtName: null,
    connum: null,
    reqDate: null,
    tax: null,
    lista: [],
    listb: [],
    listc: [],
    listd: [],
  },
  radioGroup: null,

  rules: {
    deptId: [{ required: true, message: '' }],
    vendId: [{ required: true, message: '' }],
    qty: [{ required: true, message: '' }],
    price: [{ required: true, message: '' }],
    taxPrice: [{ required: true, message: '' }],
    reqDate: [{ required: true, message: '' }],
    connum: [{ required: true, message: '' }],
  },
  model: {
    absId: '',
  },
  editableData: {
    nowDate: null,
  },
  visible: {
    approvord: false,
  },
  approvedData: {
    baseEntry: null,
    tabName: null,
  },
  itemList: [],
  chooseLinea: null,
  activeKey: '1',
  doc: {
    tm: 'saord',
    tda: 'saorda',
  },
  area: [],
});

const columnsa = ref([
  {
    title: 'BOMID',
    dataIndex: 'bomId',
    align: 'left',
    width: 160,
  },

  {
    title: 'BOM名称',
    dataIndex: 'bomName',
    align: 'left',
    width: 160,
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 160,
    align: 'right',
    resizable: true,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    width: 120,
    align: 'center',
  },


  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: 100,
    fixed: 'right',
  },
]);
const columnsb = ref([
  {
    title: '基础编码',
    dataIndex: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '基础行号',
    dataIndex: 'lineNum',
    width: 250,
    align: 'right',
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 300,
    align: 'right',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'right',
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 120,
    align: 'right',
  },
]);
const columnsc = ref([
  {
    title: '目标编码',
    dataIndex: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '目标行号',
    dataIndex: 'lineNum',
    width: 250,
    align: 'right',
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    width: 300,
    align: 'right',
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    width: 300,
    align: 'right',
  },
  {
    title: '数量',
    dataIndex: 'qty',
    width: 120,
    align: 'right',
  },
]);
const tableLoading = ref(false);

const formRef = ref(null);

// 初始化
function init() {
  if (route.query.type === 'info') {
    data.form.id = route.query.id;
    queryData();
  } else {
    data.form.edit = true;
  }
}

// 更多操作
function more({ key }) {
  // 审核处理函数
  if (key === 'a') {
    data.form.docStatus = 'C';
    tableLoading.value = true;
    saordApi.update(data.form).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  } else if (key === 'b') {
    data.form.docStatus = 'O';
    tableLoading.value = true;
    saordApi.update(data.form).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  } else if (key === 'c') {
    approvordApi
      .add({
        id: 0,
        approvLineNum: 2,
        approvType: 'A',
        baseEntry: data.form.id,
        tabName: data.form.objName,
        docStatus: 'O',
        tabId: data.form.objId,
        baseVersion: data.form.version,
      })
      .then((res) => {
        queryData();
      });
  } else if (key === 'd') {
    approvordApi
      .add({
        id: 0,
        approvLineNum: 2,
        approvType: 'B',
        baseEntry: data.form.id,
        tabName: data.form.objName,
        docStatus: 'O',
        tabId: data.form.objId,
        baseVersion: data.form.version,
      })
      .then((res) => {
        queryData();
      });
  } else if (key === 'e') {
    router.push({ path: 'prporda', query: { type: 'tager', id: data.form.id } });
  } else if (key === 'f') {
    router.push({ path: 'subordaback', query: { type: 'tager', id: data.form.id } });
  }
}

function save() {
  tableLoading.value = true;
  formRef.value
    .validate()
    .then(() => {
      if (data.form.id) {
        saordApi
          .update(data.form)
          .then((res) => {
            queryData(data.form.id);
            message.success('修改成功！');
          })
          .finally(() => {
            tableLoading.value = false;
          });
      } else {
        saordApi
          .add(data.form)
          .then((res) => {
            data.form.id = res.data;
            message.success('保存成功！');
            router.push({ path: 'saorda', query: { type: 'info', id: res.data } });
            queryData(res.data);
          })
          .finally(() => {
            tableLoading.value = false;
          });
      }
    })
    .catch((err) => {
      tableLoading.value = false;
      message.error('页面校验失败！');
    });
}

function edit() {
  if (data.form.listc.length !== 0) {
    message.error('存在生产计划，禁止编辑！');
  } else {
    data.form.edit = true;
  }
}

function del() {
  if (data.form.listc.length !== 0) {
    message.error('存在生产计划，禁止编辑！');
  } else {
    Modal.confirm({
      content: `确认删除（${data.form.id}）`,
      onOk() {
        saordApi.delete(data.form.id).then((res) => {
          message.success('删除成功！');
          router.push({ path: data.doc.tm });
        });
      },
      cancelText: '取消',
      onCancel() {
        Modal.destroyAll();
      },
    });
  }
}

function queryData() {
  tableLoading.value = true;
  bomordApi
    .info(data.form.id)
    .then((res) => {
      data.tableData = res.data;
    })
    .catch((e) => {
      smartSentry.captureError(e);
    })
    .finally(() => {
      tableLoading.value = false;
    });
}

function refresh() {
  queryData();
}

function back() {
  router.push({ path: 'saord' });
}

function change(item, key) {
  data.form.deptName = key;
}

function vendChange(item, key) {
  data.area[0] = key.province;
  data.area[1] = key.city;
  data.area[2] = key.district;

  data.form.province = key.province;
  data.form.provinceName = key.provinceName;
  data.form.city = key.city;
  data.form.cityName = key.cityName;
  data.form.district = key.district;
  data.form.districtName = key.districtName;

  data.form.vendId = item;
  data.form.vendName = key.enterpriseName;
  data.form.tax = key.tax;
  data.form.address = key.address;
  data.form.contact = key.contact;
  data.form.contactPhone = key.contactPhone;
}

function changeArea(value, selectedOptions) {
  Object.assign(data.form, {
    province: '',
    provinceName: '',
    city: '',
    cityName: '',
    district: '',
    districtName: '',
  });
}

function changeCascader() {
  console.log(data.area);
}

// 审核------------------------------------------------------------------------------------------------
function approved() {
  data.approvedData.baseEntry = data.form.id;
  data.approvedData.tabName = data.form.objName;
  data.visible.approvord = true;
}

function onclose() {
  data.visible.approvord = false;
  queryData();
}

// 行----------------------------------------------a-------------------------------------------------------

function priceChange(item) {
  item.taxPrice = (item.price * item.tax).toFixed(2);
  item.priceLine = (item.qty * item.price).toFixed(2);
  item.taxPriceLine = (item.price * item.tax * item.qty).toFixed(2);
}

function taxPriceChange(item) {
  item.price = (item.taxPrice / item.tax).toFixed(2);
  item.priceLine = (item.qty * item.price).toFixed(2);
  item.taxPriceLine = (item.taxPrice * item.qty).toFixed(2);
}

function qtyChange(item) {
  item.priceLine = (item.qty * item.price).toFixed(2);
  item.taxPriceLine = (item.taxPrice * item.tax * item.qty).toFixed(2);
}

function itemFocus(item) {
  data.chooseLinea = item;
}

function itemChange(item, it) {
  data.chooseLinea.itemName = it.key.goodsName;
  data.chooseLinea.specs = it.key.specs;
  data.chooseLinea.unit = it.key.unit;
}

function queryItemList() {
  goodsApi
    .queryGoodsList({
      pageNum: 1,
      pageSize: 10,
    })
    .then((res) => {
      data.itemList = res.data.list;
    })
    .catch((err) => { })
    .finally(() => { });
}

function lineaEdit(key) {
  key.edit = true;
}

function lineaAdd() {
  data.form.lista.push({
    id: data.form.id,
    lineNum: data.form.lista.length + 1,
    lineStatus: 'O',
    qty: 0.01,
    reqDate: data.form.reqDate,
    tax: data.form.tax,
    invQty: 0,
    price: 0,
    priceLine: 0,
    taxPrice: 0,
    taxPriceLine: 0,
    edit: true,
  });
}

function lineaDel(item) {
  data.form.lista.splice(item.lineNum - 1, 1);
  for (let i = item.lineNum - 1; i < data.form.lista.length; i++) {
    data.form.lista[i].lineNum = data.form.lista[i].lineNum - 1;
  }
}

// --------------------------------凭证

function showForm(data, it) {
  router.push({ path: it, query: { type: 'info', id: data.id } });
}

function handleResizeColumn(w, col) {
  col.width = w;
}

const expandedRowKeys = ref([]);
function changeExand(val) {
  expandedRowKeys.value = val;
}


const formModal = ref();
function addCategory(parentId, rowData) {
  formModal.value.showModal(1, parentId, rowData);
}

function reloadList(parentId) {

  if (parentId) {
    expandedRowKeys.value.push(parentId);
  }
}
onMounted(() => {
  init();
});
</script>
